<?php

namespace App\Http\Middleware\Auth;

use Closure;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;

class JWTRoleAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param null $role
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $role = null)
    {
        if (!$request->header('Authorization')){
            return response()->json(['code'=>1001,'msg'=>'缺少token参数']);
        }

        try {
            $token_role = JWTAuth::parseToken()->getClaim('role');
            if ($token_role != $role) {
                return response()->json(['code'=>'1001','msg'=>'token role error']);
            }


        }catch (TokenExpiredException $exception){

            try {

                return response()->json(['code'=>1002,'msg'=>'token过期','token'=>JWTAuth::refresh()]);
            }catch (JWTException $exception){

                return response()->json(['code'=>1001,'msg'=>'token verify failed']);
            }

        }catch (TokenInvalidException $exception){

            return response()->json(['code'=>1001,'msg'=>'token验证失败']);
        }

        return $next($request);
    }
}
